import 'package:flutter/material.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:xiaofanshu_flutter/model/pixel_art.dart';
import 'package:cached_network_image/cached_network_image.dart';

/// 像素画地图覆盖组件
/// 用于在地图上显示像素画
class PixelArtOverlay extends StatelessWidget {
  final PixelArt pixelArt;
  final AMapController mapController;
  final double currentZoom;
  final VoidCallback? onTap;

  const PixelArtOverlay({
    super.key,
    required this.pixelArt,
    required this.mapController,
    required this.currentZoom,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Offset?>(
      future: _convertLatLngToScreenPosition(),
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data == null) {
          return const SizedBox.shrink();
        }

        final screenPosition = snapshot.data!;
        final size = _calculateScreenSize();

        return Positioned(
          left: screenPosition.dx - size.width / 2,
          top: screenPosition.dy - size.height / 2,
          child: GestureDetector(
            onTap: onTap,
            child: Transform.rotate(
              angle: pixelArt.rotation * 3.14159 / 180, // 转换为弧度
              child: Opacity(
                opacity: pixelArt.opacity,
                child: Container(
                  width: size.width,
                  height: size.height,
                  decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2),
                        blurRadius: 5,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: CachedNetworkImage(
                    imageUrl: pixelArt.imageUrl,
                    fit: BoxFit.contain,
                    placeholder: (context, url) => Container(
                      color: Colors.grey.withOpacity(0.3),
                      child: const Center(
                        child: CircularProgressIndicator(),
                      ),
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: Colors.grey.withOpacity(0.3),
                      child: const Icon(Icons.error),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 将经纬度转换为屏幕坐标
  Future<Offset?> _convertLatLngToScreenPosition() async {
    try {
      final screenCoordinate = await mapController.toScreenLocation(
        LatLng(pixelArt.latitude, pixelArt.longitude),
      );
      return Offset(
        screenCoordinate.x.toDouble(),
        screenCoordinate.y.toDouble(),
      );
    } catch (e) {
      return null;
    }
  }

  /// 根据地图缩放级别计算屏幕尺寸
  /// 
  /// 原理：
  /// 1. 像素画有实际物理尺寸（米）
  /// 2. 根据地图缩放级别，计算1米对应多少像素
  /// 3. 实际尺寸 × 米/像素比例 = 屏幕像素
  Size _calculateScreenSize() {
    // 高德地图缩放级别与比例尺的关系
    // zoom level 3-19
    // 每级缩放，比例尺约变化2倍
    // zoom 18: 1米 ≈ 5像素
    // zoom 17: 1米 ≈ 2.5像素
    // zoom 16: 1米 ≈ 1.25像素
    
    final metersPerPixel = _getMetersPerPixel(currentZoom);
    
    final widthInPixels = pixelArt.width / metersPerPixel;
    final heightInPixels = pixelArt.height / metersPerPixel;

    // 限制最小和最大尺寸
    final clampedWidth = widthInPixels.clamp(20.0, 500.0);
    final clampedHeight = heightInPixels.clamp(20.0, 500.0);

    return Size(clampedWidth, clampedHeight);
  }

  /// 根据缩放级别获取每像素对应的米数
  double _getMetersPerPixel(double zoom) {
    // 高德地图的比例尺计算
    // zoom 3: 1像素 ≈ 40075000米
    // zoom 18: 1像素 ≈ 0.6米
    // 公式：metersPerPixel = 40075000 / (256 * 2^zoom)
    
    const earthCircumference = 40075000.0; // 地球赤道周长（米）
    return earthCircumference / (256 * (1 << zoom.toInt()));
  }
}

/// 像素画管理器 Widget
/// 用于在地图上管理多个像素画的显示
class PixelArtManager extends StatefulWidget {
  final List<PixelArt> pixelArts;
  final AMapController mapController;
  final double currentZoom;
  final Function(PixelArt)? onPixelArtTap;

  const PixelArtManager({
    super.key,
    required this.pixelArts,
    required this.mapController,
    required this.currentZoom,
    this.onPixelArtTap,
  });

  @override
  State<PixelArtManager> createState() => _PixelArtManagerState();
}

class _PixelArtManagerState extends State<PixelArtManager> {
  @override
  Widget build(BuildContext context) {
    // 按 zIndex 排序，确保正确的叠加顺序
    final sortedPixelArts = List<PixelArt>.from(widget.pixelArts)
      ..sort((a, b) => a.zIndex.compareTo(b.zIndex));

    return Stack(
      children: sortedPixelArts.map((pixelArt) {
        return PixelArtOverlay(
          key: ValueKey(pixelArt.id),
          pixelArt: pixelArt,
          mapController: widget.mapController,
          currentZoom: widget.currentZoom,
          onTap: () => widget.onPixelArtTap?.call(pixelArt),
        );
      }).toList(),
    );
  }
}

